<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <script>
    function deepCopy(obj) {
      if (typeof obj !== "object") return obj;
      let newObj = Array.isArray(obj) ? [] : {};
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          newObj[key] = typeof obj[key] === "object" ? deepCopy(obj[key]) : obj[key];
        }
      }
      return newObj;
    }
    function deepCopy2(obj, hash = new WeakMap()) {
      // 如果不是对象类型，直接返回
      if (typeof obj !== "object" || obj === null) {
        return obj;
      }

      // 检查是否已经是循环引用过的对象
      if (hash.has(obj)) {
        return hash.get(obj);
      }

      // 根据对象类型创建新对象
      let newObj;
      if (Array.isArray(obj)) {
        newObj = [];
      } else if (obj instanceof Date) {
        return new Date(obj.getTime());
      } else if (obj instanceof RegExp) {
        return new RegExp(obj);
      } else if (obj instanceof Function) {
        return obj;
      } else {
        newObj = {};
      }

      // 记录当前对象
      hash.set(obj, newObj);

      // 遍历对象属性
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          newObj[key] = deepCopy(obj[key], hash);
        }
      }

      return newObj;
    }
    let obj = {
      name: "obj",
      age: 18,
      father: {
        name: "father",
        age: 30,
      },
    };
    console.log("obj: ", obj);
    let newObj = deepCopy(obj);
    console.log("newObj: ", newObj);
    newObj.name = "newObj";
    newObj.father.age = 35;
    console.log("after obj: ", obj);
    console.log("after newObj: ", newObj);

  </script>
</body>

</html>